package com.cl;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: CL
 * @Date: 2023-06-27   17:16
 * @Description: 是一个ByteBuffer读写模式切换和读ByteBuffer数据并打印的案例
 */
@Slf4j
public class ChannelDemo1 {

    public static void main(String[] args) {

        try(RandomAccessFile file = new RandomAccessFile("D:\\workSpace\\netty-study\\data.txt","rw")){
            FileChannel channel = file.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(10);

            while (true) {
                //向buffer写入数据
                int len = channel.read(buffer);
                log.debug("读到字节数{}",len);

                if(len == -1 ) break;

                //切换到读模式
                buffer.flip();
                while (buffer.hasRemaining()){
                    log.debug("{}",(char)buffer.get());
                }

                //切换到buffer写模式 , 不然下一个循环不能写入数据
                buffer.clear();
            }

        }catch (IOException e){
            e.printStackTrace();
        }


    }

}
